package com.jzo2o.customer.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.ChainWrappers;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.AgencyCertificationAuditMapper;
import com.jzo2o.customer.mapper.AgencyCertificationMapper;
import com.jzo2o.customer.mapper.ServeProviderMapper;
import com.jzo2o.customer.model.domain.AgencyCertification;
import com.jzo2o.customer.model.domain.AgencyCertificationAudit;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.domain.WorkerCertification;
import com.jzo2o.customer.model.dto.AgencyCertificationUpdateDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditAddReqDTO;
import com.jzo2o.customer.service.IAgencyCertificationService;
import com.jzo2o.mvc.utils.UserContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 机构认证信息表 服务实现类
 * </p>
 */
@Service
public class AgencyCertificationServiceImpl extends ServiceImpl<AgencyCertificationMapper, AgencyCertification> implements IAgencyCertificationService {
    @Resource
    private ServeProviderMapper serveProviderMapper;
    @Resource
    private AgencyCertificationAuditMapper agencyCertificationAuditMapper;
    @Resource
    private AgencyCertificationMapper agencyCertificationMapper;

    /**
     * 根据机构id更新
     *
     * @param agencyCertificationUpdateDTO 机构认证更新模型
     */
    @Override
    public void updateByServeProviderId(AgencyCertificationUpdateDTO agencyCertificationUpdateDTO) {
        LambdaUpdateWrapper<AgencyCertification> updateWrapper = Wrappers.<AgencyCertification>lambdaUpdate()
                .eq(AgencyCertification::getId, agencyCertificationUpdateDTO.getId()) // 机构id
                .set(AgencyCertification::getCertificationStatus, agencyCertificationUpdateDTO.getCertificationStatus()) // 认证状态
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getName()), AgencyCertification::getName, agencyCertificationUpdateDTO.getName()) // 机构名称
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getIdNumber()), AgencyCertification::getIdNumber, agencyCertificationUpdateDTO.getIdNumber()) // 机构id
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getLegalPersonName()), AgencyCertification::getLegalPersonName, agencyCertificationUpdateDTO.getLegalPersonName()) // 法人名称
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getLegalPersonIdCardNo()), AgencyCertification::getLegalPersonIdCardNo, agencyCertificationUpdateDTO.getLegalPersonIdCardNo()) // 法人id
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getBusinessLicense()), AgencyCertification::getBusinessLicense, agencyCertificationUpdateDTO.getBusinessLicense()) // 营业执照
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getCertificationTime()), AgencyCertification::getCertificationTime, agencyCertificationUpdateDTO.getCertificationTime()); // 认证时间
        super.update(updateWrapper);
    }

    /**
     * 机构端 - 提交认证申请
     *
     * @param agencyCertificationAuditAddReqDTO 机构认证信息
     */
    @Override
    public void addCertificationInfoForAgency(AgencyCertificationAuditAddReqDTO agencyCertificationAuditAddReqDTO) {
        //1、获取当前登录机构的id
        Long userId = UserContext.currentUserId();
        //2、根据当前登录用户的id，查询当前机构信息
        ServeProvider agency = serveProviderMapper.selectById(userId);
        if (ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(agency)) {
            throw new ForbiddenOperationException("机构不存在无法认证");
        }
        if (agency.getType() != UserType.INSTITUTION) {
            throw new ForbiddenOperationException("提交认证资料不符合机构身份");
        }

        //3、接下来要更新 agency_certification_audit 表、 agency_certification 表
        //3.1、更新 agency_certification_audit(机构认证审核表)
        agencyCertificationAuditMapper.insert(AgencyCertificationAudit.builder()
                .serveProviderId(agency.getId()) //机构id
                .businessLicense(agencyCertificationAuditAddReqDTO.getBusinessLicense()) //营业执照
                .legalPersonIdCardNo(agencyCertificationAuditAddReqDTO.getLegalPersonIdCardNo()) //法人身份证号码
                .idNumber(agencyCertificationAuditAddReqDTO.getIdNumber()) //统一社会信用代码
                .legalPersonName(agencyCertificationAuditAddReqDTO.getLegalPersonName()) //法人名称
                .name(agencyCertificationAuditAddReqDTO.getName()) //机构名称
                .build());
        //3.2、更新 agency_certification(机构认证表)的认证状态
        // --- 首先要审核通过才会去存储全部机构信息，目前只变更认证状态。通过之前均从审核表获取信息
        // 构建 AgencyCertification 对象，设置ID和认证状态为"处理中"
        AgencyCertification agencyCertification = AgencyCertification.builder()
                .id(userId)
                .certificationStatus(CertificationStatusEnum.PROGRESSING.getStatus()) // 审核状态设为认证中
                .build();
        // 检查数据库中是否存在该ID的记录
        if (ChainWrappers.lambdaQueryChain(agencyCertificationMapper)
                .eq(AgencyCertification::getId, userId)
                .count() == 0) {
            // 不存在则插入新记录
            agencyCertificationMapper.insert(agencyCertification);
        } else {
            // 存在则更新记录
            agencyCertificationMapper.updateById(agencyCertification);
        }

    }


}
